<?php

namespace app\model;

use think\Model;

class Fence extends Model
{
    const IS_DELETE_NO = 0; // 未删
    const HARDWARE_NORMAL = 1; // 硬件正常
    const HARDWARE_ABNORMAL = 0; // 硬件异常

    const STATUS_NORMAL = 10;
    const STATUS_ABNORMAL = 20;

    /**
     * @Description 关联生猪表
     * @author: zj
     * @time 2024/03/20 14:52:45
     * @return \think\model\relation\HasMany
     */
    public function pig()
    {
        return $this->hasMany('pig',"out_fence_id","out_id");
    }

    /**
     * @Description 判断第三方主键是否存在
     * @author: zj
     * @param int $factoryId
     * @param int $outId
     * @time 2024/03/11 17:36:12
     * @return false|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function checkOutIdIsExist(int $factoryId, int $outId)
    {
        $info = $this->field('id')
            ->where('factory_id',$factoryId)
            ->where('out_id',$outId)
            ->where('delete_time',self::IS_DELETE_NO)
            ->find();
        if (!$info) {
            return false;
        }

        return $info['id'];
    }

    /**
     * @Description 检查猪栋中猪栏是否存在
     * @author: zj
     * @param int $outBarnId
     * @param string $name
     * @time 2024/03/11 17:39:47
     * @return false|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function checkNameIsExist(int $outBarnId,string $name)
    {
        $info = $this->field('id')
            ->where('out_barn_id',$outBarnId)
            ->where('name',$name)
            ->where('delete_time',self::IS_DELETE_NO)
            ->find();
        if (!$info) {
            return false;
        }

        return $info['id'];
    }

    /**
     * @Description 统计猪栏数量
     * @param int $factoryId
     * @param int $barnId
     * @param int $status
     * @time 2024/03/20 17:38:49
     * @return int
     * @throws \think\db\exception\DbException
     *@author: zj
     */
    public function checkFenceCount(int $factoryId,int $barnId = 0,int $status = -1): int
    {
        $query = $this
            -> where('factory_id',$factoryId)
            -> where('delete_time',self::IS_DELETE_NO);
        if ($barnId) {
            $query -> where('out_barn_id',$barnId);
        }
        if ($status > -1) {
            $query -> where('status',$status);
        }
        return $query -> count() ?? 0;
    }

}